package com.ruoyi.project.socket.packet;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class L1Header {
    //魔数0xAB,8bit
    private byte magic = (byte) 0xAB;

    //保留，占2bit（值：0~3）
    private byte reserve;

    //错误标志，占1bit（值：0~1）
    private byte errFlag;

    //ACK标志，占1bit（值：0~1）
    private byte ackFlag;

    //版本，占4bit，（值：0~15）
    private byte version;

    //负载长度，占2字节
    private short payloadLen;

    //检验码，占2字节
    private short crc16;

    //序号，占2字节
    private short seqId;

    public int getLen(){
        return 8;
    }

    public byte[] l1Header2Bytes(){
        ByteBuf buf = Unpooled.buffer(8);
        buf.writeByte(magic);
        buf.writeByte(calTwiceByte());
        buf.writeShort(payloadLen);
        buf.writeShort(crc16);
        buf.writeShort(seqId);
        return buf.array();
    }

    private byte calTwiceByte(){
        return (byte) (version+ackFlag*2+errFlag*4);
    }

    public byte getErrFlag() {
        return errFlag;
    }

    public void setErrFlag(byte errFlag) {
        if(errFlag<0||errFlag>1){
            log.info("l1 errFlag只可以取0~1");
            return;
        }
        this.errFlag = errFlag;
    }

    public byte getAckFlag() {
        return ackFlag;
    }

    public void setAckFlag(byte ackFlag) {
        if(ackFlag<0||ackFlag>1){
            log.info("l1 ackFlag只可以取0~1");
            return;
        }
        this.ackFlag = ackFlag;
    }

    public byte getVersion() {
        return version;
    }

    public void setVersion(byte version) {
        if(version<0||version>15){
            log.info("l1 version只可以取0~15");
            return;
        }
        this.version = version;
    }

    public short getPayloadLen() {
        return payloadLen;
    }

    public void setPayloadLen(short payloadLen) {
        this.payloadLen = payloadLen;
    }

    public short getCrc16() {
        return crc16;
    }

    public void setCrc16(short crc16) {
        this.crc16 = crc16;
    }

    public short getSeqId() {
        return seqId;
    }

    public void setSeqId(short seqId) {
        this.seqId = seqId;
    }

    @Override
    public String toString() {
        return "L1Header{" +
                "magic=" + magic +
                ", reserve=" + reserve +
                ", errFlag=" + errFlag +
                ", ackFlag=" + ackFlag +
                ", version=" + version +
                ", payloadLen=" + payloadLen +
                ", crc16=" + crc16 +
                ", seqId=" + seqId +
                '}';
    }
}
